<template>
  <el-drawer
    v-model="modalVisible"
    direction="rtl"
    size="800"
    :append-to-body="true"
    :show-close="false"
    @close-auto-focus="closeDialog()"
  >
    <template #header>
      <h4>{{ dialogType == FormTypeEnum.EDIT ? "编辑" : "新增" }}参数</h4>
    </template>
    <template #default>
      <div class="drawer-body-lock">
        <el-form
          ref="ruleFormRef"
          :model="row"
          status-icon
          append-to-body
          label-width="auto"
          class="demo-ruleForm"
          :rules="formRules"
        >
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item prop="code" label="参数名">
                <el-input v-model="row.code" />
              </el-form-item>
              <el-row :gutter="24">
                <el-col :span="10">
                  <el-form-item prop="recordType" label="是否为数组">
                    <el-switch
                      v-model="row.recordType"
                      style="--el-switch-off-color: #909399"
                      :active-value="RecordTypeEnum.Array"
                      :inactive-value="RecordTypeEnum.Base"
                      :active-icon="Check"
                      inline-prompt
                      @change="dateTypeChange"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item v-if="row.recordType !== RecordTypeEnum.Base" prop="separator" label="参数连接符">
                    <el-input v-model="row.separator" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="name" label="参数描述">
                <el-input v-model="row.name" type="textarea" :rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="16">
              <el-form-item>
                <el-radio-group v-model="row.type" @change="typeChange">
                  <el-radio value="base">基本类型</el-radio>
                  <el-radio value="enum">数据结构（枚举）</el-radio>
                  <el-radio value="class">数据结构（类）</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="footerDiv">
                <el-input v-model="searchKey" placeholder="请输入搜索内容" class="csc-search-input" clearable @change="searchEvent">
                  <template #append>
                    <el-button :icon="Search" @change="searchEvent" />
                  </template>
                </el-input>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <div class="drawertable-content">
          <vxe-grid class="drawer-grid" highlight-hover-row auto-resize show-overflow ref="typeTreeTable" height="auto" border="none" :loading="loading" :data="list" :radio-config="{ highlight: true, trigger: 'row' }" :columns="tableColumn">
          </vxe-grid>
        </div>
      </div>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button plain @click="closeDialog">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="confirmEvent">确 定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { Search, Check } from "@element-plus/icons-vue"
import { searchStructDataApi } from "@@/apis/basic-data/index";
import { listDatatype } from "@@/apis/basic-type/index";
import { BasicClassField, BasicClassValueField, BSTableData, PageTableRequestData } from "@@/apis/basic-data/types";
import { BSDataTypeEnum, FormTypeEnum, RecordTypeEnum } from "@@/constants/other-keys";
import { cloneDeep } from "lodash";
import { ref, nextTick } from "vue";
import { VxeGridPropTypes } from "vxe-table";
import XEUtils from "xe-utils";
import { BasicTypeInfo } from "@@/apis/basic-type/types";
import { watch } from "vue";

interface Props {
  visible: boolean;
  staticFlag: number;
  dialogType: FormTypeEnum;
  defaultInfo?: BasicClassField;
}
const props = defineProps<Props>()
const emits = defineEmits(['handleConfirm', 'closeDialog'])
const DEFAULT_ITEM_VALUE: BasicClassField = {
  id: undefined,
  name: undefined,
  code: undefined,
  type: BSDataTypeEnum.Base,
  typeId: undefined,
  typeCode: undefined,
  separator: undefined,
  recordType: RecordTypeEnum.Base,
  staticFlag: props.staticFlag,
  value: ""
}
const typeTreeTable = ref();
const row = ref<BasicClassField>(cloneDeep(DEFAULT_ITEM_VALUE))
const modalVisible = ref<boolean>(false)
const loading = ref<boolean>(false)
const searchKey = ref<string>()
const tableData = ref<BSTableData[] | BasicTypeInfo[]>([])
const list = ref<BSTableData[] | BasicTypeInfo[]>([])
const baseDatas = ref<BasicTypeInfo[]>([])
const structData = ref<BSTableData[]>([])
const tableColumn = ref<VxeGridPropTypes.Columns>([])
const structColumn = ref<VxeGridPropTypes.Columns>([
  { type: 'radio', width: 60 },
  { field: 'id', title: '标识', visible: false },
  { field: 'code', title: '标识', align: "left" },
  { field: 'name', title: '辅助标识', align: "left" },
  { field: 'description', title: '描述', showOverflow: true, align: "left" }
])
const baseColumn = ref<VxeGridPropTypes.Columns>([
  { type: 'radio', width: 60 },
  { field: 'id', title: '标识', visible: false },
  { field: 'value', title: '标识' },
  { field: 'label', title: '辅助标识' },
])
const formRules = ref({
  code: [{ required: true, message: '请输入参数名', trigger: 'blur' }],
  recordType: [{ required: true, message: '请选择数据类型', trigger: 'blur' }]
})

const getBaseDatas = () => {
  return new Promise((resolve) => {
    listDatatype({}).then(({ data }) => {
      baseDatas.value = data;
      tableData.value = cloneDeep(baseDatas.value);
      resolve(data)
    })
  })
}
const dateTypeChange = () => {
  if (row.value.recordType == RecordTypeEnum.Array) {
    row.value.separator = ";";
    formRules.value.separator = [{ required: true, message: '请输入', trigger: 'blur' }]
  } else {
    row.value.separator = "";
    delete formRules.value.separator
  }
}
const typeChange = async () => {
  switch (row.value.type) {
    case BSDataTypeEnum.Base:
      await getBaseDatas();
      tableColumn.value = cloneDeep(baseColumn.value);
      tableData.value = cloneDeep(baseDatas.value);
      break;
    case BSDataTypeEnum.Enum:
      await getStructDataPromise();
      tableColumn.value = cloneDeep(structColumn.value);
      tableData.value = structData.value;
      typeTreeTable.value.loadData(tableData.value);
      break;
    case BSDataTypeEnum.Class:
      await getStructDataPromise();
      tableColumn.value = cloneDeep(structColumn.value);
      tableData.value = structData.value;
      typeTreeTable.value.loadData(tableData.value);
  }
  handleSearch()
  nextTick(() => {
    let currentRow = XEUtils.find(tableData.value, item => item.id == row.value.typeId);
    currentRow && typeTreeTable.value && typeTreeTable.value.setRadioRow(currentRow);
  })
}
const getStructDataPromise = (): Promise<BSTableData[]> => {
  return new Promise(resolve => {
    const params : PageTableRequestData = {
      type: row.value.type,
      code: searchKey.value
    }
    searchStructDataApi(params).then(({ data }) => {
      structData.value = data.rows
      resolve(data.rows)
    }).catch(() => {
      structData.value = []
      resolve([])
    })
  })
}

const showDialog = () => {
  nextTick(() => {
    searchKey.value = undefined;
    if (props.dialogType == FormTypeEnum.EDIT) {
      if (props.defaultInfo) {
        row.value = cloneDeep(props.defaultInfo);
      }
    } else {
      row.value = cloneDeep(DEFAULT_ITEM_VALUE);
    }
    typeChange();
  })
}
const confirmEvent = () => {
  const selectRecord = typeTreeTable.value.getRadioRecord()
  if (selectRecord != null) {
    row.value.typeCode = (row.value.type !== BSDataTypeEnum.Base ? selectRecord.code : selectRecord.value);
    if (row.value.recordType == RecordTypeEnum.Array) {
      row.value.typeCode = "DA_" + row.value.typeCode;
    }
    row.value.typeId = selectRecord.id;
  }
  emits("handleConfirm", row.value)
  modalVisible.value = false
}
const closeDialog = () => {
  emits("closeDialog")
}
const handleSearch = () => {
  if (searchKey.value != undefined) {
    const filterVal = String(searchKey.value).trim().toLowerCase()
    let searchProps: string[] = []
    if (row.value.type == BSDataTypeEnum.Base) {
      searchProps = ['value', 'label']
    } else {
      searchProps = ['name', 'code', 'description', 'value', 'label']
    }
    const rest = tableData.value.filter(item => searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1))
    list.value = rest.map(row => {
      // 搜索为克隆数据，不会污染源数据
      const item = XEUtils.clone(row)
      return item
    })
  } else {
    list.value = tableData.value
  }
}

const searchEvent = XEUtils.throttle(function () {
  handleSearch()
}, 500, { trailing: true, leading: true })


watch(
  () => props.visible,
  () => {
    modalVisible.value = props.visible
    if (modalVisible.value) {
      showDialog()
    }
  }
)
</script>

<style lang="scss" scoped>
.csc-search-input {
  width: 300px;
}
.edit-down-modal {
  display: flex;
  align-items: center;
}

.edit-popup-button {
  width: 60px;
}

.edit-down-pulldown {
  width: auto;
  flex-grow: 1;
}

:deep(.edit-down-input .vxe-input--inner) {
  border-radius: 4px 0 0 4px;
}

.mytable-scrollbar .vxe-radio--label {
  display: block;
}

.footerDiv {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: var(--main-padding);
}
</style>
